import base64
import datetime
import random
import uuid

import numpy
from Illumination import Illumination
from Observation import *
from PostProcessing import PostProcessing
from SceneObjects import SceneObject
from Sensor import *
from Simulation import Simulation
from OpticalProperty import OpticalItem
# sys.path.append(r"D:\LESS\app\Python_script\pyLessSDK")
from SimulationHelper import SimulationHelper
from Terrain import TERRAIN_TYPE, TERRAIN_BRDF_TYPE
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from util.util import UtilD
from ObjectGenerator_depressed import CrownShape, LAD, LeafShape, CrownGenerator

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:1234@localhost:3306/cesiumfiresys'
app.config['SQLALCHEMY_POOL_SIZE'] = 20
db = SQLAlchemy(app)
uploadPath = "D:\study_home\CesiumData\lessData\positionTxT"
uploadPath_cluster = "D:\study_home\CesiumData\lessData\clusterFile"
uploadPath_HyperspectralView = "D:\study_home\CesiumData\lessData\HyperspectralViewFile"
uploadPath_WindChartView = "D:\study_home\CesiumData\lessData\WindChartView"
uploadPath_Endelement = "D:\study_home\CesiumData\lessData\Endelement"
uploadPath_Endelement2 = "D:\study_home\CesiumData\lessData\Endelement2"
uploadPath_MaximumAbundanceClassification = "D:\study_home\CesiumData\lessData\MaximumAbundanceClassification"
uploadPath_Fourcomponent = "D:\study_home\CesiumData\lessData\Fourcomponent"
uploadPath_liuyanImg = "D:\study_home\CesiumData\lessData\liuyanImg"
uploadPath_generate_model = "D:\study_home\CesiumData\lessData\generate_model"
Nginx_less_path = "http://127.0.0.1/CesiumData/lessData/"


class Users(db.Model):
    uid = db.Column(db.String(255))
    account = db.Column(db.String(500), primary_key=True)
    uname = db.Column(db.String(500), unique=True, nullable=False)
    password = db.Column(db.String(500), unique=True, nullable=False)
    phone = db.Column(db.String(500), unique=True, nullable=False)
    address = db.Column(db.String(500), unique=True, nullable=False)
    remarks = db.Column(db.String(500), unique=True, nullable=False)
    status = db.Column(db.Integer(), unique=True, nullable=False)


class Lessmodle(db.Model):
    uuid = db.Column(db.String(500), primary_key=True)
    user = db.Column(db.String(500), unique=True, nullable=False)
    position = db.Column(db.Text(), unique=True, nullable=False)
    url = db.Column(db.Text(), unique=True, nullable=False)
    fileUrl = db.Column(db.Text(), unique=True, nullable=False)
    type = db.Column(db.Integer(), unique=True, nullable=False)
    createTime = db.Column(db.DateTime(), unique=True, nullable=False)


class Liuyan(db.Model):
    uid = db.Column(db.String(500), primary_key=True)
    username = db.Column(db.String(500), unique=True, nullable=False)
    text = db.Column(db.Text(), unique=True, nullable=False)
    filecode = db.Column(db.String(500), unique=True, nullable=False)
    filename = db.Column(db.String(500), unique=True, nullable=False)
    fileurl = db.Column(db.String(500), unique=True, nullable=False)
    createtime = db.Column(db.DateTime(), unique=True, nullable=False)


@app.route('/')
def hello_world():  # put application's code here
    return jsonify({"code": 200, "msg": "成功test", "data": {"name": "13350491234", "msg": 'Hello World!'}})


@app.route('/user/login', methods=['POST'])
def login():
    username = request.args.get("username")
    password = request.args.get("password")
    count = Users.query.filter_by(account=username, password=password).count()
    print("查询个数", count, username, password)
    if count > 0:
        user = Users.query.filter_by(account=username, password=password).first()
        print(user)
        return jsonify(
            code=200,
            msg="登陆成功",
            data={
                "uid": user.uid,
                "uname": user.uname,
                "account": user.account,
                "phone": user.phone,
                "address": user.address,
                "remarks": user.remarks,
                "status": user.status,
                # "password": user.password,
            })
    else:
        return jsonify(code=201, msg="账号密码错误", data="")


@app.route('/user/register', methods=['POST'])
def register():
    account = request.args.get("account")
    password = request.args.get("password")
    uname = request.args.get("uname")
    phone = request.args.get("phone")
    address = request.args.get("address")
    remarks = request.args.get("remarks")
    status = 0
    print(account, password, uname, phone, address, remarks)
    uid = uuid.uuid1()
    while Users.query.filter_by(uid=uid).count() > 1:
        uid = uuid.uuid1()
    count = Users.query.filter_by(account=uname).count()
    if count != 0:
        return jsonify(
            code=200,
            msg="该账户存在",
            data={
                "account": account,
                "password": password,
            })
    else:
        user = Users(uid=uid, uname=uname,
                     password=password, account=account,
                     phone=phone, address=address,
                     remarks=remarks, status=status)
        db.session.add(user)
        db.session.commit()
        return jsonify(
            code=200,
            msg="注册成功",
            data={
                "uid": user.uid,
                "uname": user.uname,
                "account": user.account,
            })


# 测试数组转换功能
@app.route('/user/upload', methods=['POST'])
def upload():
    data = request.args.get("data")
    print(data, type(data))
    x = numpy.array(json.loads(','.join(data.split()).replace('[,', '[').replace('nan', 'NaN')))
    y = numpy.array2string(x).replace("\n", "").replace(" ", ",")

    print(x, type(x), y)
    return jsonify(code=200, msg="成功", data=y)


@app.route('/user/getData', methods=['POST'])
def getInfo():
    uid = request.args.get("token")
    print("token:", uid)
    user = Users.query.filter_by(uid=uid).first()
    if user == None:
        return jsonify(
            code=200,
            msg="查询成功",
            data={
                "uid": "",
                "uname": "",
                "account": "",
                "phone": "",
                "address": "",
                "remarks": "",
                "status": -1,
                # "password": user.password,
            })
    else:
        return jsonify(
            code=200,
            msg="查询成功",
            data={
                "uid": user.uid,
                "uname": user.uname,
                "account": user.account,
                "phone": user.phone,
                "address": user.address,
                "remarks": user.remarks,
                "status": user.status,
                "password": user.password,
            })


@app.route('/user/updateUser', methods=['POST'])
def updateUser():
    uid = request.args.get("uid")
    account = request.args.get("account")
    password = request.args.get("password")
    uname = request.args.get("uname")
    phone = request.args.get("phone")
    address = request.args.get("address")
    remarks = request.args.get("remarks")
    print(uid, password, uname)
    user = Users.query.filter_by(uid=uid).first()
    if user == None:
        return jsonify(
            code=200,
            msg="更新失败，无此账号",
            data={
                "uid": "",
                "uname": "",
                "account": "",
                "phone": "",
                "address": "",
                "remarks": "",
                "status": -1,
                # "password": user.password,
            })
    else:
        user.account = account
        user.password = password
        user.uname = uname
        user.phone = phone
        user.address = address
        user.remarks = remarks
        db.session.commit()
        return jsonify(
            code=200,
            msg="修改成功",
            data={
                "uid": user.uid,
                "uname": user.uname,
                "account": user.account,
                "phone": user.phone,
                "address": user.address,
                "remarks": user.remarks,
                "status": user.status,
                # "password": user.password,
            })


@app.route('/user/getHistoryList', methods=['POST'])
def getHistoryList():
    uid = request.args.get("token")
    print("token:", uid)
    user = Users.query.filter_by(uid=uid).first()
    print(user)
    if user is None:
        return jsonify(
            code=201,
            msg="查询无此用户",
            data={
                "uid": "",
                "uname": "",
                "account": "",
                "phone": "",
                "address": "",
                "remarks": "",
                "status": -1,
                # "password": user.password,
            })
    else:
        account = user.account
        print(account)
        lessModel = Lessmodle.query.filter_by(user=account).all()
        print(lessModel)
        res = []
        for item in lessModel:
            res.append({
                "uuid": item.uuid,
                "user": item.user,
                "url": item.url,
                "type": item.type,
                "createTime": item.createTime.strftime("%Y-%m-%d %H:%M:%S"),
                "fileUrl": item.fileUrl,
            })
        return jsonify(
            code=200,
            msg="查询成功",
            data=res)


# 游客使用
@app.route('/user/createLessTourist', methods=['POST'])
def createLessPngTourist():
    quality = request.args.get("quality")
    currentPath = "D:\study_home\CesiumData\lessData\lessProject"  # 项目路径
    print(currentPath)
    fileCount = len(os.listdir(currentPath))
    print("当前已生成n个模型", fileCount)
    sim_dir = r"D:\study_home\CesiumData\lessData\lessProject\project0" + str(fileCount + 1)
    print("项目路径", sim_dir)

    sim_helper = SimulationHelper(r"D:\LESS")
    sim_helper.create_new_sim(sim_dir)
    sim = Simulation(sim_dir, sim_helper)
    sim.read_sim_project()
    scene = sim.get_scene()
    landscape = scene.get_landscape()
    landscape.clear_landscape_elements()
    landscape.clear_user_defined_optical_properties()
    # 定义树木对象
    obj = SceneObject(r"tree01")  # Define an object
    obj.add_component_from_file(r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_leaves.obj",
                                "birch_leaf_green")
    obj.add_component_from_file(r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_trunk.obj",
                                "birch_branch")
    obj.add_component_from_file(r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_branch.obj",
                                "birch_branch")
    landscape.add_object(obj)

    for i in range(30):
        x = random.random() * 100
        y = random.random() * 100
        landscape.place_object("tree01", x=x, y=y, z=0, rotate=0)

    terrain = landscape.get_terrain()
    terrain.set_extent_width(100)
    terrain.set_extent_height(100)
    terrain.set_terrain_type(TERRAIN_TYPE.PLANE)
    terrain.set_terr_brdf_type(TERRAIN_BRDF_TYPE.LAMBERTIAN)
    terrain.set_optical(r"dark_soil_mollisol")
    # If you want to open the simulation with GUI, please uncomment this following line
    # sim.prepare_for_ui()

    # Illumination
    illu = Illumination()
    illu.set_sun_zenith(45)
    illu.set_sun_azimuth(90)
    # The type can be SKY_TO_TOTAL or ATMOSPHERE
    illu.set_ats_type("SKY_TO_TOTAL")
    illu.set_ats_percentage(
        "0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0")
    scene.set_illumination(illu)

    # Sensor
    # !Note that scene.set_sensor(sensor) should be executed after sensor setup is complete!
    sensor = SensorOrthographic()
    sensor.set_film_type("rgb")
    sensor.set_spectral_bands(
        "368.33:1,385.00:1,401.67:1,418.33:1,435.00:1,451.67:1,468.33:1,485.00:1,501.67:1,518.33:1,535.00:1,551.67:1,568.33:1,585.00:1,601.67:1,618.33:1,635.00:1,651.67:1,668.33:1,685.00:1,701.67:1,718.33:1,735.00:1,751.67:1,768.33:1,785.00:1,801.67:1,818.33:1,835.00:1,851.67:1")
    if quality == "low":
        sensor.set_image_width(40)
        sensor.set_image_height(40)
    else:
        sensor.set_image_width(300)
        sensor.set_image_height(300)
    sensor.set_sample_per_pixel(16)
    sensor.has_four_components_product = False
    sensor.has_Fluor_Product = 0
    sensor.set_sub_region_width(100)
    sensor.set_sub_region_height(100)
    sensor.cover_whole_scene = False
    sensor.set_repetitive_scene(100)

    scene.set_sensor(sensor)

    obs = ObservationOrthographic()
    obs.set_obs_zenith(0)
    obs.set_obs_azimuth(180)
    obs.is_orthophoto_map = False
    obs.orthophoto_relative_height = 0
    scene.set_observation(obs)

    # Advanced Parameter
    scene.get_advanced_params().set_number_of_cores(5)  # How many CPU cores used to do simulation

    # Simulation
    # You can use sim.set_dist_file to customize the final file name
    # You can use PostProcessing.radiance2brf to convert radiance image to BRF image
    sim.save_sim_project()
    sim.start()
    PostProcessing.radiance2brf(sim.get_sim_dir(), sim.get_dist_file(), sim.get_dist_file() + "_BRF")

    url = "http://127.0.0.1/CesiumData/lessData/lessProject/project0" + str(
        fileCount + 1) + "/Results/spectral_VZ=0_VA=180.png"
    print(url)
    uid = uuid.uuid1()
    return jsonify(code=200, msg="less建模成功", data={"url": url, "uuid": uid})


# 游客使用
@app.route('/user/createLessHdrTourist', methods=['POST'])
def createLessHdrTourist():
    currentPath = "D:\study_home\CesiumData\lessData\lessProject"  # 项目路径
    print(currentPath)
    fileCount = len(os.listdir(currentPath))
    print("当前已生成n个模型", fileCount)
    sim_dir = r"D:\study_home\CesiumData\lessData\lessProject\project0" + str(fileCount + 1)
    print("项目路径", sim_dir)

    sim_helper = SimulationHelper(r"D:\LESS")
    sim_helper.create_new_sim(sim_dir)
    sim = Simulation(sim_dir, sim_helper)
    sim.read_sim_project()
    scene = sim.get_scene()
    landscape = scene.get_landscape()
    landscape.clear_landscape_elements()
    landscape.clear_user_defined_optical_properties()

    # 定义树木对象
    obj = SceneObject(r"tree01")  # Define an object
    obj.add_component_from_file(r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_leaves.obj",
                                "birch_leaf_green")
    obj.add_component_from_file(r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_trunk.obj",
                                "birch_branch")
    obj.add_component_from_file(r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_branch.obj",
                                "birch_branch")
    landscape.add_object(obj)

    for i in range(30):
        x = random.random() * 100
        y = random.random() * 100
        landscape.place_object("tree01", x=x, y=y, z=0, rotate=0)
    terrain = landscape.get_terrain()
    terrain.set_extent_width(100)
    terrain.set_extent_height(100)
    terrain.set_terrain_type(TERRAIN_TYPE.PLANE)
    terrain.set_terr_brdf_type(TERRAIN_BRDF_TYPE.LAMBERTIAN)
    terrain.set_optical(r"dark_soil_mollisol")

    # Illumination
    illu = Illumination()
    illu.set_sun_zenith(45)
    illu.set_sun_azimuth(90)
    # The type can be SKY_TO_TOTAL or ATMOSPHERE
    illu.set_ats_type("SKY_TO_TOTAL")
    illu.set_ats_percentage("0.0,0.0")
    scene.set_illumination(illu)

    sensor = SensorOrthographic()
    sensor.set_film_type("spectrum")
    # sensor.set_film_type("rgb")
    sensor.set_spectral_bands("600:2,900:2")
    sensor.set_image_width(100)
    sensor.set_image_height(100)
    sensor.set_sample_per_pixel(128)
    sensor.has_four_components_product = False
    sensor.has_Fluor_Product = 0
    sensor.set_sub_region_width(100)
    sensor.set_sub_region_height(100)
    sensor.cover_whole_scene = False
    sensor.set_repetitive_scene(100)
    scene.set_sensor(sensor)

    obs = ObservationOrthographic()
    obs.set_obs_zenith(0)
    obs.set_obs_azimuth(180)
    obs.is_orthophoto_map = False
    obs.orthophoto_relative_height = 0
    scene.set_observation(obs)

    # Advanced Parameter
    scene.get_advanced_params().set_number_of_cores(12)  # How many CPU cores used to do simulation

    # Simulation
    # You can use sim.set_dist_file to customize the final file name
    # You can use PostProcessing.radiance2brf to convert radiance image to BRF image
    sim.save_sim_project()
    sim.start()
    PostProcessing.radiance2brf(sim.get_sim_dir(), sim.get_dist_file(), sim.get_dist_file() + "_BRF")

    url = "http://127.0.0.1/CesiumData/lessData/lessProject/project0" + str(
        fileCount + 1) + "/Results/spectral_VZ=0_VA=180.hdr"
    print(url)
    uid = uuid.uuid1()
    return jsonify(code=200, msg="less建模成功", data={"url": url, "uuid": uid})


@app.route('/user/kemansClassify', methods=['POST'])
def kemansClassify():
    positionFileList = request.files.getlist("file")
    uid = str(uuid.uuid4())
    folder = 'clustering_results_' + uid
    result_folder = os.path.join(uploadPath_cluster, folder)
    os.makedirs(result_folder, exist_ok=True)
    fileName_Header = 'clustering_results_' + uid + "_"
    fileName_Path = ""
    for file in positionFileList:
        fileName = fileName_Header + file.filename
        fileNameArr = file.filename.split(".")
        if fileNameArr[len(fileNameArr) - 1] == "hdr":
            fileName_Path = file.filename
            print("找到了hdrUrl", fileName_Path)
        file.save(os.path.join(result_folder, fileName))
    file_Url = os.path.join(result_folder, fileName_Header + fileName_Path)
    result = UtilD.classifyKmeans(file_Url, result_folder, uid)
    all = Nginx_less_path + "/clusterFile/" + folder + "/" + result.get("all")
    grass = Nginx_less_path + "/clusterFile/" + folder + "/" + result.get("grass")
    tree01 = Nginx_less_path + "/clusterFile/" + folder + "/" + result.get("tree01")
    img = Nginx_less_path + "/clusterFile/" + folder + "/" + result.get("img")
    print("图像的nginx地址：", img)
    return jsonify(code=200, msg="丰度图查看成功",
                   data={"url": img, "fileName": result.get("img"), "all": all, "grass": grass, "tree01": tree01,
                         "arr": [{"a": "a"}, {"a": "a"}, {"a": "a"}, ]})


@app.route('/user/MaximumAbundanceClassification', methods=['POST'])
def MaximumAbundanceClassification():
    positionFileList = request.files.getlist("file")
    uid = str(uuid.uuid4())
    folder = 'Mac_' + uid
    result_folder = os.path.join(uploadPath_MaximumAbundanceClassification, folder)
    os.makedirs(result_folder, exist_ok=True)
    fileName_Header = 'Mac_' + uid + "_"
    fileName_Path = ""
    for file in positionFileList:
        fileName = fileName_Header + file.filename
        fileNameArr = file.filename.split(".")
        if fileNameArr[len(fileNameArr) - 1] == "hdr":
            fileName_Path = file.filename
            print("找到了hdrUrl", fileName_Path)
        file.save(os.path.join(result_folder, fileName))
    file_Url = os.path.join(result_folder, fileName_Header + fileName_Path)
    result = UtilD.MaximumAbundanceClassification(file_Url, result_folder, uid)
    tree = Nginx_less_path + "/MaximumAbundanceClassification/" + folder + "/" + result.get("tree")
    img = Nginx_less_path + "/MaximumAbundanceClassification/" + folder + "/" + result.get("img")
    print("图像的nginx地址：", img)
    return jsonify(code=200, msg="丰度图查看成功",
                   data={"url": img, "fileName": result.get("img"), "tree": tree, })


@app.route('/user/generate_model', methods=['POST'])
def generate_model():
    lvd = float(request.form['lvd'])
    crown_diameter_EW = float(request.form['crown_diameter_EW'])
    crown_diameter_SN = float(request.form['crown_diameter_SN'])
    crown_height = float(request.form['crown_height'])
    crown_shape_str = request.form['crown_shape'].upper()  # 将字符串转换为大写
    crown_shape = getattr(CrownShape, crown_shape_str)  # 使用getattr()函数获取枚举类型的值
    leaf_angle_dist_str = request.form['leaf_angle_dist'].upper()
    leaf_angle_dist = getattr(LAD, leaf_angle_dist_str)  # 使用getattr()函数获取枚举类型的值
    single_leaf_area = float(request.form['single_leaf_area'])
    leaf_shape_str = request.form['leaf_shape'].upper()  # 将字符串转换为大写
    leaf_shape = getattr(LeafShape, leaf_shape_str)  # 使用getattr()函数获取枚举类型的值
    has_trunk = request.form.get('has_trunk', False) == 'on'
    trunk_height = float(request.form['trunk_height']) if has_trunk else 0.0
    dbh = float(request.form['dbh']) if has_trunk else 0.0

    cg = CrownGenerator()
    cg.lvd = lvd
    cg.crown_diameter_EW = crown_diameter_EW
    cg.crown_diameter_SN = crown_diameter_SN
    cg.crown_height = crown_height
    cg.crown_shape = crown_shape
    cg.leaf_angle_dist = leaf_angle_dist
    cg.single_leaf_area = single_leaf_area
    cg.leaf_shape = leaf_shape
    cg.has_trunk = has_trunk
    cg.trunk_height = trunk_height
    cg.dbh = dbh

    uid = str(uuid.uuid4())
    folder = 'Generate_model_' + uid
    result_folder = os.path.join(uploadPath_generate_model, folder)
    os.makedirs(result_folder, exist_ok=True)
    fileName = 'Generate_model_' + uid + "_" + "crown.obj"
    file_Url = os.path.join(result_folder, fileName)
    resultPath = Nginx_less_path + "/generate_model/" + folder + "/" + fileName
    cg.generate_crown(file_Url)

    return jsonify(code=200, msg="树冠建模成功",
                   data={"url": resultPath, "fileName": fileName})


@app.route('/user/Fourcomponent', methods=['POST'])
def Fourcomponent():
    positionFileList = request.files.getlist("file")
    uid = str(uuid.uuid4())
    folder = 'FC_' + uid
    result_folder = os.path.join(uploadPath_Fourcomponent, folder)
    os.makedirs(result_folder, exist_ok=True)
    fileName_Header = 'FC_' + uid + "_"
    fileName_Path = ""
    for file in positionFileList:
        fileName = fileName_Header + file.filename
        fileNameArr = file.filename.split(".")
        if fileNameArr[len(fileNameArr) - 1] == "hdr":
            fileName_Path = file.filename
            print("找到了hdrUrl", fileName_Path)
        file.save(os.path.join(result_folder, fileName))
    file_Url = os.path.join(result_folder, fileName_Header + fileName_Path)
    result = UtilD.Fourcomponent(file_Url, result_folder, uid)
    img = Nginx_less_path + "/Fourcomponent/" + folder + "/" + result.get("img")
    print("图像的nginx地址：", img)
    return jsonify(code=200, msg="丰度图查看成功",
                   data={"url": img, "fileName": result.get("img")})


@app.route('/user/uploadLiuyan', methods=['POST'])
def uploadLiuyan():
    username = request.form.get("username")
    filecode = request.form.get("filecode")
    text = request.form.get("text")
    uid = str(uuid.uuid4())
    filename = ""
    fileurl = ""
    createtime = datetime.datetime.now()
    os.makedirs(uploadPath_liuyanImg, exist_ok=True)
    if (filecode == "1"):
        print("有图像")
        file = request.files.get("file")
        filename = uid + request.form.get("filename")
        print(file, filename, request.form.get("filename"))
        file.save(os.path.join(uploadPath_liuyanImg, filename))
        fileurl = Nginx_less_path + "/liuyanImg/" + filename
    print(uid, username, text, filecode, filename, fileurl,
          createtime)
    liuyan = Liuyan(uid=uid, username=username, text=text, filecode=filecode, filename=filename, fileurl=fileurl,
                    createtime=createtime)  # 0为png，1为hdr
    db.session.add(liuyan)
    db.session.commit()
    return jsonify(code=200, msg="留言成功",
                   data={})


@app.route('/user/fetchLiuyan', methods=['POST'])
def fetchLiuyan():
    page = int(request.form.get("page"))
    liuyanList = Liuyan.query.order_by(Liuyan.createtime.desc()).paginate(page=page, per_page=5)
    count = Liuyan.query.count()
    list = liuyanList.items
    print(len(list))
    print("获取第几页", page, liuyanList, list)
    res = []
    for e in list:
        print(e.username)
        res.append({
            "username": e.username,
            "text": e.text,
            "filecode": e.filecode,
            "filename": e.filename,
            "fileurl": e.fileurl,
            "createtime": e.createtime.strftime("%Y-%m-%d %H:%M:%S"),
        })
    return jsonify(code=200, msg="留言查询成功",
                   data={"count": count, "list": res})  # "list":list


@app.route('/user/HyperspectralView', methods=['POST'])
def HyperspectralView():
    positionFileList = request.files.getlist("file")
    index = int(request.form.get("index"))
    uid = str(uuid.uuid4())
    print(index, index - 1)
    folder = 'HyperspectralView' + uid
    result_folder = os.path.join(uploadPath_HyperspectralView, folder)
    os.makedirs(result_folder, exist_ok=True)
    fileName_Header = 'HyperspectralView' + uid + "_"
    fileName_Path = ""
    for file in positionFileList:
        fileName = fileName_Header + file.filename
        if len(file.filename) > len(fileName_Path):
            fileName_Path = file.filename
        file.save(os.path.join(result_folder, fileName))
    HDR_file_Url = os.path.join(result_folder, fileName_Header + fileName_Path)
    image_Url = os.path.join(result_folder, fileName_Header + ".png")
    res = UtilD.HyperspectralView(HDR_file_Url, result_folder, image_Url, index)
    image_nginx_path = Nginx_less_path + "/HyperspectralViewFile/" + folder + "/" + fileName_Header + ".png"
    if res.get("status"):
        return jsonify(code=200, msg="高光谱查看成功", data={"url": image_nginx_path, "fileName": fileName_Header + ".png"})
    else:
        return jsonify(code=201, msg="高光谱查看失败",
                       data={"msg": "您的高光谱数据波段一共有" + str(res.get("num_bands")) + "个，你选择的波段索引超出最大值"})


@app.route('/user/WindChartView', methods=['POST'])
def WindChartView():
    positionFileList = request.files.getlist("file")
    uid = str(uuid.uuid4())
    folder = 'WindChartView_' + uid
    result_folder = os.path.join(uploadPath_WindChartView, folder)
    os.makedirs(result_folder, exist_ok=True)  # 创建当前项目文件夹
    fileName_Header = 'WindChartView_' + uid + "_"
    fileName_Path = ""
    for file in positionFileList:
        fileName = fileName_Header + file.filename
        if len(file.filename) > len(fileName_Path):
            fileName_Path = file.filename
        file.save(os.path.join(result_folder, fileName))
    file_Url = os.path.join(result_folder, fileName_Header + fileName_Path)
    result_image_name = UtilD.WindChartView(file_Url, os.path.join(result_folder, fileName_Header + '.png'))
    image_nginx_path = Nginx_less_path + "/WindChartView/" + folder + "/" + fileName_Header + '.png'
    print("图像的nginx地址：", image_nginx_path)
    return jsonify(code=200, msg="kemans聚类成功", data={"url": image_nginx_path, "fileName": 'WindChartView_' + uid})


@app.route('/user/Endelement', methods=['POST'])
def Endelement():
    positionFileList = request.files.getlist("file")
    x = int(request.form.get("x"))
    y = int(request.form.get("y"))
    uid = str(uuid.uuid4())
    folder = 'Endelement_' + uid
    result_folder = os.path.join(uploadPath_Endelement, folder)
    os.makedirs(result_folder, exist_ok=True)  # 创建当前项目文件夹
    fileName_Header = 'Endelement_' + uid + "_"
    fileName_Path = ""
    for file in positionFileList:
        fileName = fileName_Header + file.filename
        if len(file.filename) > len(fileName_Path):
            fileName_Path = file.filename
        file.save(os.path.join(result_folder, fileName))
    file_Url = os.path.join(result_folder, fileName_Header + fileName_Path)
    result_image_name = UtilD.Endelement(file_Url, os.path.join(result_folder, fileName_Header + '.png'), x, y)
    image_nginx_path = Nginx_less_path + "/Endelement/" + folder + "/" + fileName_Header + '.png'
    print("图像的nginx地址：", image_nginx_path)
    return jsonify(code=200, msg="位置点端元图查看成功", data={"url": image_nginx_path, "fileName": fileName_Header + '.png'})


@app.route('/user/Endelement2', methods=['POST'])
def Endelement2():
    positionFileList = request.files.getlist("file")
    uid = str(uuid.uuid4())
    folder = 'Endelement2' + uid
    result_folder = os.path.join(uploadPath_Endelement2, folder)
    os.makedirs(result_folder, exist_ok=True)  # 创建当前项目文件夹
    fileName_Header = 'Endelement2' + uid + "_"
    fileName_Path = ""
    for file in positionFileList:
        fileName = fileName_Header + file.filename
        if len(file.filename) > len(fileName_Path):
            fileName_Path = file.filename
        file.save(os.path.join(result_folder, fileName))
    file_Url = os.path.join(result_folder, fileName_Header + fileName_Path)
    result_image_name = UtilD.nmtf_and_plot_endmember_spectra(file_Url,
                                                              os.path.join(result_folder, fileName_Header + '.png'))
    image_nginx_path = Nginx_less_path + "/Endelement2/" + folder + "/" + fileName_Header + '.png'
    print("图像的nginx地址：", image_nginx_path)
    return jsonify(code=200, msg="端元曲线绘制成功", data={"url": image_nginx_path, "fileName": 'Endelement2' + uid})


@app.route('/user/createLess', methods=['POST'])
def createLessPng():
    data = request.form.get("data")
    user = request.form.get("user")
    quality = request.form.get("quality")
    obs_zenith = int(request.form.get("obs_zenith"))
    obs_azimuth = int(request.form.get("obs_azimuth"))
    extend_width = int(request.form.get("extend_width"))
    extend_height = int(request.form.get("extend_height"))
    sun_zenith = int(request.form.get("sun_zenith"))
    sun_azimuth = int(request.form.get("sun_azimuth"))
    sub_region_width = int(request.form.get("sub_region_width"))
    sub_region_height = int(request.form.get("sub_region_height"))
    image_width = int(request.form.get("image_width"))
    image_height = int(request.form.get("image_height"))
    positionFile = request.files.get("file")

    print(data, user, quality, obs_azimuth, obs_zenith, extend_height, extend_width, sun_zenith, sun_azimuth,
          sub_region_height, sub_region_width, image_height, image_width)
    print(type(obs_zenith))
    # print(data ,  user , positionFile.filename , image_height)
    # return jsonify(code=201, msg="less建模成功111", data={"url": "", "uuid": "uid"})
    # -----------------------------------------------------------获取参数完毕
    x = numpy.array(json.loads(','.join(data.split()).replace('[,', '[').replace('nan', 'NaN')))

    for i in x:
        print(i)
    # y = numpy.array2string(x).replace("\n", "").replace(" ", ",")
    categoryArr = UtilD.getCategoryArr(x)
    print(categoryArr)
    objMap = {
        "tree01": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_leaves.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_trunk.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_leaves.obj",
                    "footer": "birch_branch"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_branch.obj",
                    "footer": "birch_branch", }
                   ],
        "tree02": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree02_trunk.obj",
                    "footer": "birch_branch"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree02_leaf_boundary.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree02_branch.obj",
                    "footer": "birch_branch"},
                   ],
        "grass": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\grass_grass_Grass.obj",
                   "footer": "birch_leaf_green"},
                  ],
        "tree03": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree03_leaves.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree03_stem_branch.obj",
                    "footer": "birch_branch"},
                   ],
        "house02": [
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_chimneys_chimneys_metal_dark_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_barrels_barrels_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_windows_windows_glass_window.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_boards_boards_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_windows_windows_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_walls_walls_plaster_light_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_foundation_foundation_foundation_brown_brick.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_cover_window_cover_window_plaster_sand.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_doors_doors_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_window_roof_window_roof_glass_window.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_barrels_barrels_metal_grey.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_roof_support_roof_support_wood_balls_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_balcony_balcony_plaster_light_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_roof_roof_metal_dark_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_gutters_gutters_metal_grey.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_boards_support_boards_support_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_window_roof_window_roof_metal_dark_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_chimneys_chimneys_plaster_light_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_parapets_parapets_foundation_brown_brick.obj",
                "footer": "roof"},
        ],
        "house01": [{
            "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house_house_10060_big_box_storefront__walmart_v2_Max2011.obj",
            "footer": "roof"},
        ],
        "tree04": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree04_leaves.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree04_stem_branch.obj",
                    "footer": "birch_branch"},
                   ],
        "corn_s": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\corn_s_corn_s_leaf.obj",
                    "footer": "corn"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\corn_s_corn_s_stem.obj",
                    "footer": "birch_leaf_green"},
                   ],
    }

    currentPath = "D:\study_home\CesiumData\lessData\lessProject"  # 项目路径
    print(currentPath)
    fileCount = len(os.listdir(currentPath))
    print("当前已生成n个模型", fileCount)
    sim_dir = r"D:\study_home\CesiumData\lessData\lessProject\project0" + str(fileCount + 1)
    print("项目路径", sim_dir)

    sim_helper = SimulationHelper(r"D:\LESS")
    sim_helper.create_new_sim(sim_dir)
    sim = Simulation(sim_dir, sim_helper)
    sim.read_sim_project()

    scene = sim.get_scene()
    landscape = scene.get_landscape()
    landscape.clear_landscape_elements()
    landscape.clear_user_defined_optical_properties()
    op_item = OpticalItem("roof",
                          "0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22, 0.24, 0.26, 0.28,    0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.42, 0.44, 0.46, 0.48,    0.5, 0.52, 0.54, 0.56, 0.58, 0.6, 0.62, 0.64, 0.66, 0.68;0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000;0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000",
                          1, {})
    landscape.add_op_item(op_item)  # Add optical properties
    op_item = OpticalItem("corn",
                          "0.05, 0.06, 0.08, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22,    0.24, 0.26, 0.28, 0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.42,    0.44, 0.46, 0.48, 0.5, 0.52, 0.54, 0.56, 0.58, 0.6, 0.62;0.05, 0.06, 0.08, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22,    0.24, 0.26, 0.28, 0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.42,    0.44, 0.46, 0.48, 0.5, 0.52, 0.54, 0.56, 0.58, 0.6, 0.62;0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000",
                          1, {})
    landscape.add_op_item(op_item)  # Add optical properties
    # 定义树木对象
    for category in categoryArr:
        if category in objMap.keys():
            print("遍历：", objMap.keys(), r"" + category)
            obj = SceneObject(r"" + category)  # Define an object
            for element in objMap.get(category):
                obj.add_component_from_file(element.get("header"), element.get("footer"))
            landscape.add_object(obj)
    for pos in x:
        if len(pos) == 5:
            if pos[0] in objMap.keys():
                landscape.place_object(pos[0], x=pos[1], y=pos[2], z=pos[3], rotate=pos[4])
        elif len(pos) == 8:
            landscape.place_object("tree01", x=pos[0], y=pos[1], z=pos[2], rotate=pos[3], rotate_axis_x=pos[4],
                                   rotate_axis_y=pos[5], rotate_axis_z=pos[6])
        elif len(pos) == 11:
            landscape.place_object("tree01", x=pos[0], y=pos[1], z=pos[2], rotate=pos[3], rotate_axis_x=pos[4],
                                   rotate_axis_y=pos[5], rotate_axis_z=pos[6], scale_extent_x=pos[7],
                                   scale_extent_y=pos[8], scale_extent_z=pos[9])

    terrain = landscape.get_terrain()
    # terrain.set_extent_width(100)
    # terrain.set_extent_height(100)
    terrain.set_extent_width(extend_width)
    terrain.set_extent_height(extend_height)
    terrain.set_terrain_type(TERRAIN_TYPE.PLANE)
    terrain.set_terr_brdf_type(TERRAIN_BRDF_TYPE.LAMBERTIAN)
    terrain.set_optical(r"dark_soil_mollisol")
    # If you want to open the simulation with GUI, please uncomment this following line
    # sim.prepare_for_ui()

    # Illumination
    illu = Illumination()
    illu.set_sun_zenith(sun_zenith)
    illu.set_sun_azimuth(sun_azimuth)
    # The type can be SKY_TO_TOTAL or ATMOSPHERE
    illu.set_ats_type("SKY_TO_TOTAL")
    illu.set_ats_percentage(
        "0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0")
    scene.set_illumination(illu)

    # Sensor
    # !Note that scene.set_sensor(sensor) should be executed after sensor setup is complete!
    sensor = SensorOrthographic()
    sensor.set_film_type("rgb")
    sensor.set_spectral_bands(
        "368.33:1,385.00:1,401.67:1,418.33:1,435.00:1,451.67:1,468.33:1,485.00:1,501.67:1,518.33:1,535.00:1,551.67:1,568.33:1,585.00:1,601.67:1,618.33:1,635.00:1,651.67:1,668.33:1,685.00:1,701.67:1,718.33:1,735.00:1,751.67:1,768.33:1,785.00:1,801.67:1,818.33:1,835.00:1,851.67:1")
    if quality == "low":
        sensor.set_image_width(40)
        sensor.set_image_height(40)
    else:
        sensor.set_image_width(image_width)
        sensor.set_image_height(image_height)
    sensor.set_sample_per_pixel(16)
    sensor.has_four_components_product = True
    sensor.has_Fluor_Product = 0
    sensor.set_sub_region_width(sub_region_width)
    sensor.set_sub_region_height(sub_region_height)
    sensor.cover_whole_scene = False
    sensor.set_repetitive_scene(100)

    scene.set_sensor(sensor)

    obs = ObservationOrthographic()
    obs.set_obs_zenith(obs_zenith)
    obs.set_obs_azimuth(obs_azimuth)
    obs.is_orthophoto_map = False
    obs.orthophoto_relative_height = 0
    scene.set_observation(obs)

    # Advanced Parameter
    scene.get_advanced_params().set_number_of_cores(5)  # How many CPU cores used to do simulation

    # Simulation
    # You can use sim.set_dist_file to customize the final file name
    # You can use PostProcessing.radiance2brf to convert radiance image to BRF image
    sim.save_sim_project()
    sim.start()
    PostProcessing.radiance2brf(sim.get_sim_dir(), sim.get_dist_file(), sim.get_dist_file() + "_BRF")

    url = "http://127.0.0.1/CesiumData/lessData/lessProject/project0" + str(
        fileCount + 1) + "/Results/spectral_VZ=0_VA=180.png"
    uid = str(uuid.uuid4())
    fileName = uid + "-" + positionFile.filename
    fileUrl = "http://127.0.0.1/CesiumData/lessData/positionTxT/" + fileName
    print("fileName", fileName, fileUrl, url)
    positionFile.save(os.path.join(uploadPath, fileName))

    lessmodle = Lessmodle(uuid=uid, user=user, position=data, url=url, type=0, fileUrl=fileUrl,
                          createTime=datetime.datetime.now())  # 0为png，1为hdr
    db.session.add(lessmodle)
    db.session.commit()

    return jsonify(code=200, msg="less建模成功", data={"url": url, "uuid": uid})


@app.route('/user/createLessHdr', methods=['POST'])
def createLessHdr():
    data = request.form.get("data")
    user = request.form.get("user")
    obs_zenith = int(request.form.get("obs_zenith"))
    obs_azimuth = int(request.form.get("obs_azimuth"))
    extend_width = int(request.form.get("extend_width"))
    extend_height = int(request.form.get("extend_height"))
    sun_zenith = int(request.form.get("sun_zenith"))
    sun_azimuth = int(request.form.get("sun_azimuth"))
    sub_region_width = int(request.form.get("sub_region_width"))
    sub_region_height = int(request.form.get("sub_region_height"))
    image_width = int(request.form.get("image_width"))
    image_height = int(request.form.get("image_height"))
    positionFile = request.files.get("file")

    x = numpy.array(json.loads(','.join(data.split()).replace('[,', '[').replace('nan', 'NaN')))
    for i in x:
        print(i)
    categoryArr = UtilD.getCategoryArr(x)
    print(categoryArr)
    objMap = {
        "tree01": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_leaves.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_trunk.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_leaves.obj",
                    "footer": "birch_branch"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree01_branch.obj",
                    "footer": "birch_branch", }
                   ],
        "tree02": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree02_trunk.obj",
                    "footer": "birch_branch"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree02_leaf_boundary.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree02_branch.obj",
                    "footer": "birch_branch"},
                   ],
        "grass": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\grass_grass_Grass.obj",
                   "footer": "birch_leaf_green"},
                  ],
        "tree03": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree03_leaves.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree03_stem_branch.obj",
                    "footer": "birch_branch"},
                   ],
        "house02": [
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_chimneys_chimneys_metal_dark_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_barrels_barrels_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_windows_windows_glass_window.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_boards_boards_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_windows_windows_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_walls_walls_plaster_light_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_foundation_foundation_foundation_brown_brick.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_cover_window_cover_window_plaster_sand.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_doors_doors_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_window_roof_window_roof_glass_window.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_barrels_barrels_metal_grey.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_roof_support_roof_support_wood_balls_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_balcony_balcony_plaster_light_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_roof_roof_metal_dark_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_gutters_gutters_metal_grey.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_boards_support_boards_support_wood_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_window_roof_window_roof_metal_dark_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_chimneys_chimneys_plaster_light_brown.obj",
                "footer": "roof"},
            {
                "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house02_house02_parapets_parapets_foundation_brown_brick.obj",
                "footer": "roof"},
        ],
        "house01": [{
            "header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\house_house_10060_big_box_storefront__walmart_v2_Max2011.obj",
            "footer": "roof"},
        ],
        "tree04": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree04_leaves.obj",
                    "footer": "birch_leaf_green"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\tree04_stem_branch.obj",
                    "footer": "birch_branch"},
                   ],
        "corn_s": [{"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\corn_s_corn_s_leaf.obj",
                    "footer": "corn"},
                   {"header": r"D:\软件工程\柯南GIS\三维遥感可视化\less_python_project\data\obj\corn_s_corn_s_stem.obj",
                    "footer": "birch_leaf_green"},
                   ],
    }

    currentPath = "D:\study_home\CesiumData\lessData\lessProject"  # 项目路径
    print(currentPath)
    fileCount = len(os.listdir(currentPath))
    print("当前已生成n个模型", fileCount)
    sim_dir = r"D:\study_home\CesiumData\lessData\lessProject\project0" + str(fileCount + 1)
    print("项目路径", sim_dir)

    sim_helper = SimulationHelper(r"D:\LESS")
    sim_helper.create_new_sim(sim_dir)
    sim = Simulation(sim_dir, sim_helper)
    sim.read_sim_project()
    scene = sim.get_scene()
    landscape = scene.get_landscape()
    landscape.clear_landscape_elements()
    landscape.clear_user_defined_optical_properties()

    # 定义树木对象
    for category in categoryArr:
        if category in objMap.keys():
            print("遍历：", objMap.keys(), r"" + category, objMap.get(category)[0], objMap.get(category)[1],
                  objMap.get(category)[2])
            obj = SceneObject(r"" + category)  # Define an object
            for element in objMap.get(category):
                obj.add_component_from_file(element.get("header"), element.get("footer"))
            landscape.add_object(obj)
    for pos in x:
        if len(pos) == 5:
            if pos[0] in objMap.keys():
                landscape.place_object(pos[0], x=pos[1], y=pos[2], z=pos[3], rotate=pos[4])
        elif len(pos) == 8:
            landscape.place_object("tree01", x=pos[0], y=pos[1], z=pos[2], rotate=pos[3], rotate_axis_x=pos[4],
                                   rotate_axis_y=pos[5], rotate_axis_z=pos[6])
        elif len(pos) == 11:
            landscape.place_object("tree01", x=pos[0], y=pos[1], z=pos[2], rotate=pos[3], rotate_axis_x=pos[4],
                                   rotate_axis_y=pos[5], rotate_axis_z=pos[6], scale_extent_x=pos[7],
                                   scale_extent_y=pos[8], scale_extent_z=pos[9])

    terrain = landscape.get_terrain()
    terrain.set_extent_width(extend_width)
    terrain.set_extent_height(extend_height)
    terrain.set_terrain_type(TERRAIN_TYPE.PLANE)
    terrain.set_terr_brdf_type(TERRAIN_BRDF_TYPE.LAMBERTIAN)
    terrain.set_optical(r"dark_soil_mollisol")

    # Illumination
    illu = Illumination()
    illu.set_sun_zenith(sun_zenith)
    illu.set_sun_azimuth(sun_azimuth)
    # The type can be SKY_TO_TOTAL or ATMOSPHERE
    illu.set_ats_type("SKY_TO_TOTAL")
    illu.set_ats_percentage("0.0,0.0")
    scene.set_illumination(illu)

    sensor = SensorOrthographic()
    sensor.set_film_type("spectrum")
    # sensor.set_film_type("rgb")
    sensor.set_spectral_bands("600:2,900:2")
    sensor.set_image_width(image_width)
    sensor.set_image_height(image_height)
    sensor.set_sample_per_pixel(128)
    sensor.has_four_components_product = True
    sensor.has_Fluor_Product = 0
    sensor.set_sub_region_width(sub_region_width)
    sensor.set_sub_region_height(sub_region_height)
    sensor.cover_whole_scene = False
    sensor.set_repetitive_scene(100)
    scene.set_sensor(sensor)

    obs = ObservationOrthographic()
    obs.set_obs_zenith(obs_zenith)
    obs.set_obs_azimuth(obs_azimuth)
    obs.is_orthophoto_map = False
    obs.orthophoto_relative_height = 0
    scene.set_observation(obs)

    # Advanced Parameter
    scene.get_advanced_params().set_number_of_cores(12)  # How many CPU cores used to do simulation

    # Simulation
    # You can use sim.set_dist_file to customize the final file name
    # You can use PostProcessing.radiance2brf to convert radiance image to BRF image
    sim.save_sim_project()
    sim.start()
    PostProcessing.radiance2brf(sim.get_sim_dir(), sim.get_dist_file(), sim.get_dist_file() + "_BRF")

    url = "http://127.0.0.1/CesiumData/lessData/lessProject/project0" + str(
        fileCount + 1) + "/Results/spectral_VZ=0_VA=180.hdr"
    uid = str(uuid.uuid4())
    fileName = uid + "-" + positionFile.filename
    fileUrl = "http://127.0.0.1/CesiumData/lessData/positionTxT/" + fileName
    print("fileName", fileName, fileUrl, url)
    positionFile.save(os.path.join(uploadPath, fileName))
    lessmodle = Lessmodle(uuid=uid, user=user, position=data, url=url, type=1, fileUrl=fileUrl,
                          createTime=datetime.datetime.now())  # 0为png，1为hdr
    db.session.add(lessmodle)
    db.session.commit()

    return jsonify(code=200, msg="less建模成功", data={"url": url, "uuid": uid})


@app.route("/user/getImg", methods=['POST'])
def getImg():
    imageUrl = request.args.get("url")
    img_stream = ''
    with open(imageUrl, 'rb') as img_f:
        img_stream = img_f.read()
        img_stream = base64.b64decode(img_stream).decode()
    return jsonify(code=200, msg="图片下载成功", data=img_stream)


if __name__ == '__main__':
    app.run('127.0.0.1', port=6789)
